package com.ironman.compute.consumer;

import com.ironman.common.params.YawParam;
import com.ironman.common.util.AccuracyUtil;
import com.ironman.event.properties.SysTrainingProperties;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.core.client.MqttClient;
import org.noear.snack.ONode;

import java.util.function.Consumer;

@Slf4j
public class YawConsumer extends BaseConsumer implements Consumer<ONode> {

    private Double preYaw = null;

    private final YawParam yawParam;

    public YawConsumer(YawParam yawParam, SysTrainingProperties sysTrainingProperties, MqttClient mqttClient) {
        super(sysTrainingProperties, mqttClient);
        this.yawParam = yawParam;
    }


    @Override
    public void accept(ONode data) {
        doAccept("yaw", data, (topic, dataJson, published) -> log.info("{} {} \n{}", topic, published, dataJson));
    }

    /**
     * 阈值处理
     */
    @Override
    public boolean threshold(ONode data) {
        double yaw = data.select("yaw").getDouble();
        if (preYaw == null) {
            getCounter().incrementAndGet();
            preYaw = yaw;
            data.set("tt", "t");
            return true;
        }

        Integer yawThreshold = yawParam.getYawThreshold();
        double diff = Math.abs(yaw - preYaw);
        diff = diff > 180 ? 360 - diff : diff;
        if (diff > yawThreshold) {
            getCounter().set(0);
            log.info("船首向触发对比阈值:{} 当前:{} 前一个:{} 相差:{} ", yawThreshold, yaw, preYaw, diff);
            preYaw = yaw;
            data.set("tt", "t");
            return true;
        }

        Integer countThreshold = yawParam.getCountThreshold();
        if (getCounter().incrementAndGet() >= countThreshold) {
            getCounter().set(0);
            log.info("船首向触发数量阈值:{} ", countThreshold);
            preYaw = yaw;
            data.set("tt", "c");
            return true;
        }
        return false;
    }

    @Override
    public void precision(ONode data) {
        double yaw = data.select("yaw").getDouble();
        data.set("yaw", AccuracyUtil.downDirectionInteger(yaw));
        data.set("yaw", 0);
    }
}
